package com.ryoma.Controller;


import com.ryoma.Utils.*;
import com.ryoma.dataSource.DatabaseContextHolder;
import com.ryoma.dataSource.DatabaseType;
import com.ryoma.model.*;
import com.ryoma.model.towercrane.Registrations;
import com.ryoma.service.*;
import com.ryoma.service.towercrane.RegistrationsService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;


import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.*;


@Controller
@RequestMapping(value = "/url")
public class UrlController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UrlService urlService;

    @Autowired
    private UserService userService;

    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private LogService logService;

    @Autowired
    private RegistrationsService registrationsService;

    @Autowired
    private CommonQueryService commonQueryService;

    @RequestMapping(value="/index")
    public String index(){
        return "user/index";
    }

    @RequestMapping(value="/form")
    public String form(@ModelAttribute Url entity, Model model){
        String url = "url/UrlForm";
        entity = urlService.getUrl(entity);
        model.addAttribute("url",entity);
        model.addAttribute("endPoint",entity.getEndPoint());
        return url;
    }

    @ResponseBody
    @RequestMapping(value = "/selectUrlList", produces = {"application/json;charset=UTF-8"})
    public String selectUrlList(Url url){
        String result = "false";
        /**
         * 弃用该部分。mapper调用改为最后一个方法的方式
         */
        /*List<Url> urlList = urlService.selectUrlList(url);
        if(urlList.size()>0){
            for(Url subUrl : urlList){
                String responseMsg = WebConnectorUtils.SendGET(subUrl.getUrl());
                JSONObject jsonObject = JSONObject.fromObject(responseMsg);
                String[] dataSources = subUrl.getDataSource().split("-");
                JSONArray jsonArrayData = null;
                for(String dataSource:dataSources){
                    if(jsonObject.get(dataSource).getClass().equals(JSONObject.class)){
                        jsonObject = JSONObject.fromObject(jsonObject.get(dataSource));
                    }else if(jsonObject.get(dataSource).getClass()==JSONArray.class){
                        jsonArrayData = JSONArray.fromObject(jsonObject.get(dataSource));
                    }
                }
                String[] template = subUrl.getSourceTemplate().split(",");//数据模板
                for(String dataSourceTemplate:template){
                    String[] dataTemplate = dataSourceTemplate.split("-");//对应的对象与字段名称
                    try {
                        for(int i=0;i<jsonArrayData.size();i++){
                            JSONObject rowData = jsonArrayData.getJSONObject(i);
                            Class c = Class.forName("com.ryoma.model."+dataTemplate[0]);
                            Object o = c.newInstance();
                            for(int j =1;j<dataTemplate.length;j++){
                                if(dataTemplate[j].equals("all")){
                                    Field[] fields = c.getDeclaredFields();
                                    for (Field f : fields) {
                                        if(f.getName().equals("id")){
                                            continue;
                                        }
                                        //*System.out.println("Reflaction: 【"+f.getName()+"】"+rowData.get(StringUtils.capitalize(f.getName())));*//*
                                        ReflectionUtils.invokeSetter(o,f.getName(),rowData.get(f.getName()));
                                    }
                                }else{
                                    //*System.out.println("Reflaction: 【"+data[j]+"】"+rowData.get(StringUtils.capitalize(data[j])));*//*
                                    ReflectionUtils.invokeSetter(o,dataTemplate[j],rowData.get(StringUtils.capitalize(dataTemplate[j])));
                                }
                            }

                            if(o.getClass() == Attendance.class){

                            }else if(o.getClass() == Staff.class){
                                StaffService staffService = SpringContextUtils.getBean(StaffService.class);
                                List<Staff> staffList = staffService.queryStaffList((Staff)o);
                                if(!(staffList.size()>0)){
                                    staffService.insert((Staff)o);
                                }else {
                                    staffService.update((Staff)o);
                                }
                            }else if(o.getClass() == Department.class){
                                System.out.println(((Department)o).getWe_name());
                                DepartmentService departmentService = SpringContextUtils.getBean(DepartmentService.class);
                                List<Department> list = departmentService.queryDepartmentList((Department)o);
                                if(!(list.size()>0)){
                                    departmentService.insert((Department)o);
                                }else {
                                    departmentService.update((Department)o);
                                }
                            }

                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    }
                }

            }

            result = "ok";
        }*/
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/postAttendanceList", produces = {"application/json;charset=UTF-8"})
    public String postAttendanceList(String signature, HttpServletRequest request, HttpServletResponse response){
        Log log = new Log();
        if(signature !=""){
            System.out.println(new Date().toString()+" signature:"+signature);
            User user = new User();
            user.setLoginName(Consts.BANGONGYI_loginName);
            List<User> userList = userService.queryUserList(user);
            //得到页面表单传递过来的键值对中的键所对应的值
            Enumeration<String> value = request.getParameterNames();

            StringBuffer c_signature  = new StringBuffer();
            /*String[] strs ={userList.get(0).getToken().getToken().replaceAll("\r|\n",""), request.getParameter(Consts.TIMESTAP),request.getParameter(Consts.NONCE)};*/
            /*Arrays.sort(strs);
            for(String sort:strs){
                c_signature.append(sort);
            }*/

            StringBuffer sb_result = new StringBuffer();
            /*while(value.hasMoreElements()) {
                String pa = value.nextElement();
                if(pa.contains("staff_id")){
                    sb_result.append(" ,result");
                    sb_result.append(JSONObject.fromObject(pa).toString());
                }else{

                }
            }*/
            log.setType(Consts.ATTENDANCE_TYPE);
            /*log.setToken(userList.get(0).getToken().getToken());*/

            System.out.println(new Date().toString()+" c_signature:"+c_signature.toString());
            String sha1 = DigestUtils.sha1Hex(c_signature.toString());
            System.out.println(new Date().toString()+" sha1Hex:"+DigestUtils.sha1Hex(c_signature.toString()));

           while(value.hasMoreElements()){
               String paramsName = value.nextElement();
               sb_result.append(paramsName).append(" :").append(request.getParameter(paramsName)).append(" ,");
               if(paramsName.equals(Consts.ECHOSTR)){
                   log.setResult(sb_result.toString());
                   /*logger.info(sb_result.toString());*/
                   logService.insert(log);
                   if(sha1.equals(signature)){
                       return request.getParameter(Consts.ECHOSTR);
                   }else{
                       return "error";
                   }
               }else if(paramsName.contains("staff_id")){
                   log.setResult(sb_result.toString());
                   logService.insert(log);
                   Url url = new Url();
                   url.setCode(Consts.GETATTENDANCEMSG);
                   List<Url> urlList = urlService.selectUrlList(url);
                   if(!(urlList.size()>0)){//error

                   }else {
                       url = urlList.get(0);
                       JSONObject jsonObject = JSONObject.fromObject(paramsName);
                       String[] sourceTemplate = url.getSourceTemplate().split("-");
                       Attendance attendance = new Attendance();
                       for(String source:sourceTemplate){
                           if(source.equals("Attendance"))
                               continue;
                           System.out.println(source+"|||"+jsonObject.get(source).getClass()+"|||"+jsonObject.get(source));
                           ReflectionUtils.invokeSetter(attendance,source,jsonObject.get(source));
                       }
                       attendanceService.insert(attendance);
                       checkStaffAndDepartmentMsg(attendance);
                       return "ok";
                   }
               }
           }
        }
        return "error";
    }


    private Object getReflectionEntity(Object entity,JSONObject jsonObject,String paramName){
        if(paramName.equals("id"))
            return entity;
        if(paramName.contains(Consts.PLACEHOLDER)){
            String[] dataPositions = paramName.split(Consts.PLACEHOLDER);
            Object o = jsonObject.get(dataPositions[0]);
            for(int i =1;i<dataPositions.length;i++){
                if(o.getClass() == JSONObject.class){
                    if(((JSONObject)o).get(dataPositions[i]) !=null){
                        entity = getReflectionEntity(entity,(JSONObject)o,dataPositions[i]);
                    }
                }else if(o.getClass() == JSONArray.class){

                }
            }
        }

        return entity;
    }

    private void checkStaffAndDepartmentMsg(Attendance attendance){
        Url url = new Url();
        if(attendance.getStaff_id()!=0){
            Staff staff = new Staff();
            staff.setStaff_id(attendance.getStaff_id()+"");
            List<Staff> staffList = staffService.queryStaffList(staff);
            if(staffList.size()==0){
                url.setCode(Consts.GETSTAFFMSG);
                selectUrlList(url);
                staffList = staffService.queryStaffList(staff);
                if(staffList.size()==0){
                    System.out.println("insert Staff msg error!!!");
                    return;
                }
                Department department = new Department();
                String[] departments = staffList.get(0).getWe_department().split(",");
                for(String department_We_id:departments){
                    department.setWe_id(department_We_id);
                    List<Department> departmentList = departmentService.queryDepartmentList(department);
                    if(departmentList.size()==0){
                        url.setCode(Consts.GETDEPARTMENTMSG);
                        selectUrlList(url);
                    }
                }
            }
        }
    }



    /*public Object buildEntity(Url url,JSONObject jsonObject){
        String[] dataSources = url.getDatasource().split("-");
        JSONArray jsonArrayData = null;
        for(String dataSource:dataSources){
            if(jsonObject.get(dataSource).getClass().equals(JSONObject.class)){
                jsonObject = JSONObject.fromObject(jsonObject.get(dataSource));
            }else if(jsonObject.get(dataSource).getClass()==JSONArray.class){
                jsonArrayData = JSONArray.fromObject(jsonObject.get(dataSource));
            }
        }
        String[] template = url.getSourcetemplate().split(",");//数据模板
        for(String dataSourceTemplate:template){
            String[] dataTemplate = dataSourceTemplate.split("-");//对应的对象与字段名称
            try {
                for(int i=0;i<jsonArrayData.size();i++){
                    JSONObject rowData = jsonArrayData.getJSONObject(i);
                    Class c = Class.forName("com.ryoma.model."+dataTemplate[0]);
                    Object o = c.newInstance();
                    for(int j =1;j<dataTemplate.length;j++){
                        if(dataTemplate[j].equals("all")){
                            Field[] fields = c.getDeclaredFields();
                            for (Field f : fields) {
                                if(f.getName().equals("id")){
                                    continue;
                                }
                                ReflectionUtils.invokeSetter(o,f.getName(),rowData.get(f.getName()));
                            }
                        }else{
                            ReflectionUtils.invokeSetter(o,dataTemplate[j],rowData.get(StringUtils.capitalize(dataTemplate[j])));
                        }
                    }


                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        return  new Object();
    }*/

    @RequestMapping(value = "/queryTowerCraneMsg", produces = {"application/json;charset=UTF-8"})
    public String queryTowerCraneMsg(String type){
        String result = "false";
        List<Registrations> registrationsList = registrationsService.queryRegistrationsList(new Registrations());
        if(registrationsList.size()>0){
            result  = "ok";
        }
        return result;
    }

    @RequestMapping(value = "queryUrlList4Table")
    public String queryUrlList4Table(Url url, Model model){
        String urls = "url/UrlList";
        return urls;
    }

    @ResponseBody
    @RequestMapping(value = "queryUrlList")
    public String queryUrlList(Url url){
        JSONObject jsonObject = new JSONObject();
        List<Url> list = urlService.selectUrlList(url);
        jsonObject.put("code","0");
        jsonObject.put("msg","");
        jsonObject.put("count",list.size());
        JSONArray jsonArray = new JSONArray();
        for(Url data:list){
            jsonArray.add(JsonUtils.paramsToJson(data.parseMap()));
        }
        jsonObject.put("data",jsonArray.toString());
        return jsonObject.toString();
    }

    @ResponseBody
    @RequestMapping(value = "startThread")
    public String startThread(String urlId,String userId,String endPointId){
        String result = "ok";
        Url url = new Url();
        url.setId(Long.parseLong(urlId));
        url = urlService.selectPOSTUrlList(url).get(0);
        CommonQuery commonQuery = new CommonQuery();
        commonQuery.setColumns(url.getColumns());
        commonQuery.setTableName(url.getTableName());


        DatabaseContextHolder.setDatabaseType(DatabaseType.towercrane);
        List<Map<String,Object>> dataList = commonQueryService.getResultList(commonQuery);

        return result;
    }

}
